package com.xiaomi.eco.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaomi.eco.dal.entity.EcoCompanyTaskListEntity;
import com.xiaomi.eco.dal.entity.EcoCompanyWebMappingEntity;
import com.xiaomi.eco.dal.res.CompanyAvailabilityRes;
import com.xiaomi.eco.mapper.EcoCompanyTaskListEntityMapper;
import com.xiaomi.eco.mapper.EcoMethodDimensionEntityMapper;
import com.xiaomi.eco.service.EcoCompanyTaskListEntityService;
import com.xiaomi.eco.service.EcoCompanyWebMappingEntityService;
import com.xiaomi.eco.service.EcoWeeklyMonitoringService;
import com.xiaomi.eco.service.TbEcoApplicationCompanyEntityService;
import com.xiaomi.eco.utils.EcoServiceQualityAlarm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EcoWeeklyMonitoringServiceImpl implements EcoWeeklyMonitoringService {
    private static String availabilityHundred = "100%";

    private static String availabilityZero = "0.000%";
    @Autowired
    private EcoCompanyWebMappingEntityService ecoCompanyWebMappingEntityService;

    @Autowired
    private EcoCompanyTaskListEntityService ecoCompanyTaskListEntityService;

    @Autowired
    private EcoCompanyTaskListEntityMapper ecoCompanyTaskListEntityMapper;

    @Autowired
    private EcoMethodDimensionEntityMapper ecoMethodDimensionEntityMapper;

    private static String chunmiMonitor = "https://dt.mi.com/whale/?pid=10100388#/data-bi/dashboard/99031?GFLT=~(11785718~(795764~(~'2024-07-02~'2024-07-08)~fff66301-0a72-48da-94f6-cab67bae6755___code~8))&projectId=10100388";


    HttpHeaders headers = new HttpHeaders();

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TbEcoApplicationCompanyEntityService tbEcoApplicationCompanyEntityService;

    private static ObjectMapper objectMapper = new ObjectMapper();


    LambdaQueryWrapper<EcoCompanyTaskListEntity> queryWrapper = new LambdaQueryWrapper<>();

    public void sendWeeklyMonitoringData() {
        List<EcoCompanyWebMappingEntity> ecoCompanyWebMappingEntityList = ecoCompanyWebMappingEntityService.list();
        //可用性不达标
        Map<String, Double> availabilityNotNumMap = ecoCompanyTaskListEntityMapper.couantAvailabilityNotNum().stream().collect(Collectors.toMap(CompanyAvailabilityRes::getCompanyName, CompanyAvailabilityRes::getNum));

        //慢接口
        Map<String, Double> slowNumTempMap = ecoCompanyTaskListEntityMapper.slowNumCount().stream().collect(Collectors.toMap(CompanyAvailabilityRes::getCompanyName, CompanyAvailabilityRes::getNum));
        Map<String, Double> overtotalMap = ecoMethodDimensionEntityMapper.totalSeven().stream().collect(Collectors.toMap(CompanyAvailabilityRes::getCompanyName, CompanyAvailabilityRes::getNum));
        //整体可用率
        Map<String, Double> overallAvailabilityMap = ecoMethodDimensionEntityMapper.avaliableSeven().stream().collect(Collectors.toMap(CompanyAvailabilityRes::getCompanyName, CompanyAvailabilityRes::getNum));

        //待处理
        Map<String, Double> pendingTempMap = ecoCompanyTaskListEntityMapper.pendingTempCount().stream().collect(Collectors.toMap(CompanyAvailabilityRes::getCompanyName, CompanyAvailabilityRes::getNum));

        //逾期
        Map<String, Double> overdueTaskMap = ecoCompanyTaskListEntityMapper.overdueTempCount().stream().collect(Collectors.toMap(CompanyAvailabilityRes::getCompanyName, CompanyAvailabilityRes::getNum));

        for (EcoCompanyWebMappingEntity ecoCompanyWebMappingEntity : ecoCompanyWebMappingEntityList) {
            if(ecoCompanyWebMappingEntity.getWebHook().isEmpty() || ecoCompanyWebMappingEntity.getWebHook().equals("")){
                //跳过
                continue;
            }
            double availabilityNotNumTemp = 0;
            double slowNumTemp = 0;
            String overallAvailabilityTemp = "";
            double pendingTemp = 0;
            double overdueTemp = 0;

            if (availabilityNotNumMap.containsKey(ecoCompanyWebMappingEntity.getCompanyName())) {
                //比如单独封装可用性不达标
                availabilityNotNumTemp = availabilityNotNumMap.get(ecoCompanyWebMappingEntity.getCompanyName());
            }

            if (slowNumTempMap.containsKey(ecoCompanyWebMappingEntity.getCompanyName())) {
                //比如单独封装慢接口数量
                slowNumTemp = slowNumTempMap.get(ecoCompanyWebMappingEntity.getCompanyName());
            }

            if (pendingTempMap.containsKey(ecoCompanyWebMappingEntity.getCompanyName())) {
                //单独封装待处理任务
                pendingTemp = pendingTempMap.get(ecoCompanyWebMappingEntity.getCompanyName());
            }
            if (overdueTaskMap.containsKey(ecoCompanyWebMappingEntity.getCompanyName())) {
                //单独封装延期任务
                overdueTemp = overdueTaskMap.get(ecoCompanyWebMappingEntity.getCompanyName());
            }
            String overallAvailabilityColor="red";
            if (overallAvailabilityMap.containsKey(ecoCompanyWebMappingEntity.getCompanyName()) && overtotalMap.get(ecoCompanyWebMappingEntity.getCompanyName()) > 0) {
                //单独封装整体可用性
                overallAvailabilityTemp = overallAvailabilityMap.get(ecoCompanyWebMappingEntity.getCompanyName()) == 1.0 ? availabilityHundred : addZeroForNum( overallAvailabilityMap.get(ecoCompanyWebMappingEntity.getCompanyName())*100,3);
                if(overallAvailabilityMap.get(ecoCompanyWebMappingEntity.getCompanyName())>0.9999){
                    overallAvailabilityColor="green";
                }
            }

            String weeklySummaryResult = "";
            String content = "";

            if (slowNumTemp > 0 || availabilityNotNumTemp > 0 || pendingTemp > 0 || overdueTemp > 0) {
                String overdueColor="red";
                if ((int) pendingTemp == 0 && (int) (overdueTemp) == 0) {
                    content = "【" + ecoCompanyWebMappingEntity.getCompanyAbbreviation() + "】 云服务质量概览 ";
                    overdueColor="green";
                } else if ((int) pendingTemp > 0 && (int) (overdueTemp) == 0) {
                    content = "【" + ecoCompanyWebMappingEntity.getCompanyAbbreviation() + "】 云服务质量概览 " + (int) pendingTemp + "个待办任务";
                    overdueColor="green";
                } else if ((int) pendingTemp == 0 && (int) (overdueTemp) > 0) {
                    content = "【" + ecoCompanyWebMappingEntity.getCompanyAbbreviation() + "】 云服务质量概览 (" + (int) overdueTemp + ")个逾期";

                }
                weeklySummaryResult = String.format(EcoServiceQualityAlarm.weeklySummaryDanger, String.valueOf((int) availabilityNotNumTemp), String.valueOf((int) slowNumTemp),overallAvailabilityColor, overallAvailabilityTemp, String.valueOf((int) pendingTemp),overdueColor, String.valueOf((int) overdueTemp), ecoCompanyWebMappingEntity.getTaskMonitorUrl(),content);
            } else {
                weeklySummaryResult = String.format(EcoServiceQualityAlarm.weeklySummaryHealth, String.valueOf((int) availabilityNotNumTemp), String.valueOf((int) slowNumTemp), overallAvailabilityTemp, String.valueOf((int) pendingTemp), String.valueOf((int) overdueTemp), ecoCompanyWebMappingEntity.getTaskMonitorUrl(),ecoCompanyWebMappingEntity.getCompanyAbbreviation());
            }


            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(weeklySummaryResult, headers);
            try {
                String response = restTemplate.postForObject(ecoCompanyWebMappingEntity.getWebHook(), entity, String.class);
            } catch (Exception e) {
                log.error("推送周服务监控数据失败,请求体为: {}", weeklySummaryResult);
            }
        }
    }

    public static String addZeroForNum(double num, int strLength) {
        String numStr = String.valueOf(num);
        String[] split = numStr.split("\\.");
        String s1 = split[0];
        String s2 = split[1];
        int strLen=s2.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append(s2).append("0");
                s2 = sb.toString();
                strLen = s2.length();
            }
        }else if(strLen > strLength){
            s2 = s2.substring(0,3);
        }
        return s1+"."+s2+"%";
    }
}
